// pages/my/index.js
import { updateNews,addNews} from "../../api/news";

Page({
  data: {
   
    EditNews:{
      id:'',
      title:'',
      content:''
    },
    categories:["桂电新闻","活动通知","校园快讯"],
    selectedCategory:'',
    selectedDepartment:'',
    departments:["桂电教务处","保卫处","编辑处"],
    isEdit:1
   
    
  },

  
  

  onCategoryChange(e) {
    this.setData({
      selectedCategory: this.data.categories[e.detail.value],
    });
  },

 


 
 

  onLoad(options){
    this.setData({
    isEdit:options.isEdit,
     EditNews:options,
     selectedDepartment:options.publisher,
     selectedCategory:options.category
    });
    console.log('---s',this.data.isEdit);

  },

 // 处理标题输入
 onTitleInput: function(e) {
  this.setData({
    'EditNews.title': e.detail.value // 更新标题
  });
},

// 处理类别选择
onCategoryChange: function(e) {
  const selectedCategory = this.data.categories[e.detail.value];
  this.setData({
    selectedCategory: selectedCategory // 更新选择的类别
  });
},

// 处理部门选择
onDepartmentChange: function(e) {
  const selectedDepartment = this.data.departments[e.detail.value];
  this.setData({
    selectedDepartment: selectedDepartment // 更新选择的部门
  });
},
 // 处理内容输入
 onContentInput: function(e) {
  this.setData({
    'EditNews.content': e.detail.value 
  });
},

// 保存操作
async save() {
  const { notificationId,title, content } = this.data.EditNews;
  const { selectedCategory, selectedDepartment } = this.data;
  console.log('_---',this.data.isEdit);
  if(this.data.isEdit==1){
    const newsData = {
      notificationId,
      title,
      content,
      category: selectedCategory,
      department: selectedDepartment
    };
    const res=await updateNews(newsData)
    if(res.code===200){
      wx.showToast({
        title: '修改成功',
        icon: 'success',
      });
      wx.navigateTo({
        url: '/pages/manage_news/index' 
      })
    }
  }
  else{
    
    const newsData = {
      title,
      content,
      category: selectedCategory,
      department: selectedDepartment
    };
    if (!newsData.title || !newsData.content || !newsData.category || !newsData.department) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none', // 使用无图标提示
        duration: 2000 // 提示持续时间
      });
      return; // 中止后续操作
    }else{
      const res=await addNews(newsData)
      if(res.code===200){
        wx.showToast({
          title: '发布成功',
          icon: 'success',
        });
        wx.navigateTo({
          url: '/pages/manage_news/index' 
        })
      }
    }
   
  }
}
  

});
